package cn.hengzhu.main_manager.web.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import cn.hengzhu.main_manager.repository.dao.CustomersMapper;
import cn.hengzhu.main_manager.repository.dao.SysConstMapper;
import cn.hengzhu.main_manager.repository.domain.ManageUser;
import cn.hengzhu.main_manager.repository.domain.SysConst;
import cn.hengzhu.main_manager.repository.domain.SysConstExample;
import cn.hengzhu.main_manager.repository.param.ContentParam;
import cn.hengzhu.main_manager.repository.param.SendTextParam;
import cn.hengzhu.main_manager.repository.vo.WeiXinErrcodeVO;
import cn.hengzhu.main_manager.service.ManageCaseService;
import cn.hengzhu.main_manager.utils.AjaxResult;
import cn.hengzhu.main_manager.utils.DateTimeHelper;
import cn.hengzhu.main_manager.utils.HttpClientUtil;
import cn.hengzhu.main_manager.utils.UserContext;
import cn.hengzhu.main_manager.utils.ann.MoblieUrl;
import cn.hengzhu.main_manager.utils.config.gzh.WeiXinConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "8公众号群发消息")
@Controller
@RequestMapping("/message")
public class MessageController {
	@Autowired
	private CustomersMapper customersMapper;
	@Autowired
	private SysConstMapper sysConstMapper;
	@Autowired
	private ManageCaseService manageCaseService;
	
	@Autowired
	private HttpServletRequest request;
	
	@MoblieUrl
	@RequestMapping("/text")
	public String text(){
		return request.getAttribute("moblie")+"messageText";
	}
	
	@MoblieUrl
	@RequestMapping("/image")
	public String image(){
		return request.getAttribute("moblie")+"messageImage";
	}
	
	
	
	@ApiOperation("发送文本消息")
	@RequestMapping("/sendText")
	@ResponseBody
	public AjaxResult sendText(@ApiParam(required = true, name = "content", value = "消息类容")String content,
			@ApiParam(required = true, name = "users", value = "接收消息的人  1：今天的用户，2：一周内的用户， 3：一个月内的用户，  4：全部")Integer users){
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		
		if(users !=null ){
			String startTime=null;
			String endTime=null;
			if(users.equals(1)){//今天
				startTime=DateTimeHelper.formatDateTimetoString(date, "yyyy-MM-dd 00:00:00"); // 当天开始时间
				endTime=DateTimeHelper.formatDateTimetoString(date, "yyyy-MM-dd 23:59:59");
			}else if(users.equals(2)){//一周内
				calendar.add(Calendar.WEEK_OF_YEAR, -1);
				Date time = calendar.getTime();
				startTime=DateTimeHelper.formatDateTimetoString(time, "yyyy-MM-dd HH:mm:ss");
				endTime=DateTimeHelper.formatDateTimetoString(date, "yyyy-MM-dd HH:mm:ss");
				
			}else if(users.equals(3)){//一个月内的用户
				calendar.add(Calendar.MONTH, -1);
				Date time = calendar.getTime();
				startTime=DateTimeHelper.formatDateTimetoString(time, "yyyy-MM-dd HH:mm:ss");
				endTime=DateTimeHelper.formatDateTimetoString(date, "yyyy-MM-dd HH:mm:ss");
			}

			List<String> userList=customersMapper.getUserByTime(compId,startTime,endTime);
			List<String> collect = userList.stream().distinct().collect(Collectors.toList()); //去重

			// 判断消息是否为空
			if(StringUtils.isNoneBlank(content)){
				SendTextParam sendTextParam = new SendTextParam();
				ContentParam contentParam = new ContentParam();
				contentParam.setContent(content);
				sendTextParam.setText(contentParam);
				sendTextParam.setTouser(collect);
				String jsonString = JSONObject.toJSONString(sendTextParam); //序列为json

				//获取token
				SysConstExample example = new SysConstExample();
				example.createCriteria().andNameEqualTo("ACCESS_TOKEN"); // NAME =
				List<SysConst> sysConst = sysConstMapper.selectByExample(example);
				String accessToken= sysConst.get(0).getValue();
				String url = WeiXinConst.SEND_MESSAGE.replace("ACCESS_TOKEN", accessToken); // 将ACCESS_TOKEN替换为 accessToken
				String httpPost = HttpClientUtil.httpPost(url, jsonString); // 发送消息
				
				
				WeiXinErrcodeVO parseObject = JSONObject.parseObject(httpPost, WeiXinErrcodeVO.class);
				String errcode = parseObject.getErrcode();
				String errmsg = parseObject.getErrmsg();
				
				if(errcode.equals("0")){
					return new AjaxResult("发送成功，接收人数为"+collect.size()+"人");
				}else if(errcode.equals("40130")){
					return new AjaxResult("当前选择接收人数少于一人，不能进行群发操作，请重新选择");
					
				}else if(errcode.equals("42001")){//重新获取token
					manageCaseService.getToken();
					return new AjaxResult("发送失败请重试");
					
				}else{
					
					return new AjaxResult("错误码："+errcode+"错误信息："+errmsg+"请联系管理员");
				}

				
			}else{
				return new AjaxResult("请输入内容");
			}
			
		}else{
			return new AjaxResult("请选择接收人");
		}
	}


	
	@RequestMapping("/uploadImage")
	@ResponseBody
	public void uploadImage(HttpServletRequest request, MultipartFile file) throws Exception{
		
		Map<String,Object> map=new HashMap<>();
		//获取token
		SysConstExample example = new SysConstExample();
		example.createCriteria().andNameEqualTo("ACCESS_TOKEN");
		List<SysConst> sysConst = sysConstMapper.selectByExample(example);
		String accessToken= sysConst.get(0).getValue();
		map.put("media", file);
		map.put("access_token", accessToken);
		String jsonString = JSONObject.toJSONString(map);
		

		//获取图片上传的url
		String url = WeiXinConst.UPLOAD_IMAGE.replace("ACCESS_TOKEN", accessToken);
		String httpPost = HttpClientUtil.httpPost(url, jsonString);
		System.out.println(httpPost);
		
		
	}
	
	
	

}
